package com.ufo.all.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

// 自定义的 UserRealm     继承 AuthorizingRealm
public class MyRealm extends AuthorizingRealm {



    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行授权");

        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");
//        info.addStringPermission("user:update");

//        拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
//        User currentUser = (User) subject.getPrincipal();

//        设置当前用户的权限
        info.addStringPermission("add:one");

        return info;
    }


    //    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //连接真实的数据库
//        User user=userService.queryUserByUserName(userToken.getUsername());
//        if (user==null){
//            //没有这个人
//            return null;
//        }
        //在已登录用户的session上保存用户的信息
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("userKey","user对象");

        //密码认证，由shiro做~~~
        return new SimpleAuthenticationInfo("username","password","MyRealm");
    }
}
